/**
 * 管理地图、飞机、子弹、敌人
 * Author:  suyuyi
 * Date:    2017.4.16
 */
cc.Class({
    extends: cc.Component,

    onLoad: function(){
        // var MapLayer = new (require("mm"))();　

        // this._layer = new cc.Node("layer_play_palyer");             // 玩家角色层
        // this.hero = null;
        // this.node.addChild(this._layer);

        this.refreshTime = 2;
        this.refreshEnemyTime = 0;
         // 游戏状态相关参数
        this.gameStatus = {
            refreshTime: 2, // 敌人刷新间隔，秒
        },
       // cc.find("background",this.node).setContentSize(2000,1000);
        // 地图相关参数，包括地图大小、边界等信息
        this.bg = cc.find("background",this.node);
        cc.find("background/Map",this.node).addComponent("Map1");
        this.map = cc.find("background/Map",this.node);
        this.map.setContentSize(2000,1000);
      
        cc.log("map:"+this.map.getPosition());
        // 玩家实例引用
       // MapLayer.createPlayer();
        this.player = cc.find("background/plane_hero",this.node);
        // this.player = this.createPlayer();
        // cc.log(this.player);
        // var nod = cc.find("layer_play_palyer",this.node);
        // cc.log(nod.getChildByTag(1001));
        // cc.log(nod);
        // this.player = cc.find("plane_hero",this.node);
        // this.player.addComponent("plane1");
        this.plane = this.player.getComponent("plane1");
        cc.log("plane:"+this.player.getPosition());
        this.joystick = cc.find("joystick",this.node);
        this.joystick.addComponent("joystick1");
        this.player.on("position-changed", function(event){                         // 飞机移动驱动地图滚屏
            this.bg.x = -event.currentTarget.x;
            this.bg.y = -event.currentTarget.y;
        }, this);

        // 攻击键
        cc.find("btn_attack", this.node).on(cc.Node.EventType.TOUCH_END   , this._onTouchEnd, this);
        cc.find("btn_attack", this.node).on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
        
        // 加速键
        cc.find("btn_speed", this.node).on(cc.Node.EventType.TOUCH_END   , this._onTouchEnd, this);
        cc.find("btn_speed", this.node).on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
        // 子弹实例引用
        this.bulletMap = {};
        this.bullet = null;
        // 敌人实例引用
        this.enemyMap = {};

        // 刷新敌人冷却时间
        this.refreshEnemyTime = 0;

        // 子弹可用的 id （每生成一个子弹 id + 1)
        this.bulletValidId = 0;

        // 敌人可用的 id （每生成一个敌人 id + 1)
        this.enemyValidId = 0;
        this.setMapInfo(new cc.Vec2(2000, 1000));

        this.node.on("joystick_move",this.planeMove,this);
        
    },
    planeMove: function(event){
        var angle = event.getUserData().angle;
        var angleHero = angle *  (180 / Math.PI); //转换为度
        this.plane.avatar.rotation = -angleHero;
        this.plane.heroMove(angle);
    },
    /** 战斗技能按钮 */
    _onTouchEnd : function(event){
        switch(event.target.name){
            case "btn_attack":
                this.createBullet();
                cc.log("plane:"+this.player.getPosition());
                cc.log("map:"+this.map.getPosition());
                break;
            case "btn_speed":
                this.plane.speed();           // 改变玩家飞行速度    
                break;
        }
    },
    createPlayer : function() {
        var prefab = cc.loader.getRes("persist/plane_hero", cc.Prefab);
        var player = cc.instantiate(prefab);
        this._layer.addChild(player);
        return player;
       
    },

    /**
     * 开始游戏。manager 将开始主循环计算
     */
    startGame: function(){
        cc.director.getScheduler().scheduleUpdate(this, 0, false, this.update.bind(this));
    },

    // 设置地图相关配置信息
    setMapInfo: function(size){
        this.map.size = size;
        this.map.rect = cc.rect(-size.x / 2, -size.y / 2, size.x, size.y);
    },

    /**
     * 设置主角实例引用
     * param: player，主角实例引用
     */
    setPlayer: function(player){
        this.player = player;
    },

    /**
     * 添加子弹到管理器中
     * param: bullet，子弹实例
     */
    addBullet: function(bullet){
        // 保存子单显示对象
        this.bulletMap[bullet.id] = bullet;
    },

    /**
     * 添加敌人到管理器中
     * param: enemy，敌人实例
     */
    addEnemy: function(enemy){
        // 保存敌人显示对象
        this.enemyMap[enemy.id] = enemy;
    },

    /**
     * 创建子弹
     */
    createBullet: function(){
        var pos = this.player.getPosition();
        cc.loader.loadRes('persist/prefab/effect_bullet', function(err, prefab){
        var bullet       = cc.instantiate(prefab);
        bullet.id        = this.bulletValidId++;                     // 攻击目标编号
        bullet.setPosition(this.player.getPosition());
        bullet.direct    = Math.angleToRadian(-this.plane.getPlaneRotation());
        bullet.speed     = 8;
        cc.log("zidan:"+bullet.getPosition());
        //this.plane.addBullet(bullet);
        this.map.addChild(bullet);
        this.addBullet(bullet);
        }.bind(this));
       
    },

    /**
     * 每帧循环控制，遍历子弹与敌人并进行碰撞检测
     */
    update: function(dt){
        
        // 更新子弹位置
        this.updateBulletPos(this.bulletMap, dt);

        // 检查子弹是否击中
        this.checkHit(this.bulletMap, this.enemyMap);

        // 刷新敌人
         this.refreshEnemy(dt);
    },

    /**
     * 更新子弹位置
     * param: bulletMap，子弹实例的 map
     *      dt，经过的时间
     */
    updateBulletPos: function(bulletMap){
        for (var key in bulletMap){
            var bullet = bulletMap[key];            
            var pos    = bullet.getPosition();
            bullet.setPositionX(pos.x + bullet.speed * Math.cos(bullet.direct));
            bullet.setPositionY(pos.y + bullet.speed * Math.sin(bullet.direct));

            // 子弹移动到地图以外
            if (! this.map.rect.contains(bullet.getPosition())){
                cc.log("attack")
                bullet.parent.removeChild(bullet, true);
                delete bulletMap[key];
            }
        }
    },

    /**
     * 检测碰撞，若发生碰撞将发出碰撞消息 ENEMY_HIT
     * param：bulletMap，子弹实例的 map
     *      planeMap，飞机实例的 map
     */
    checkHit: function(bulletMap, planeMap){
        // 验证所有子弹是否碰到飞机
        var _this = this;
        for (var bulletKey in bulletMap){
            var bullet = bulletMap[bulletKey];

            for (var planeKey in planeMap){    
                var plane = planeMap[planeKey];
                
                // 检查碰撞
                if (plane.getBoundingBox().contains(bullet.getPosition())){
                    // 触发攻击特效
                    cc.loader.loadRes('persist/prefab/effect_hit', function(err, prefab){
                        var enemy      = cc.instantiate(prefab);
                        enemy.setPosition(plane.x, plane.y);
                        enemy.targetId = plane.id;                     // 攻击目标编号
                        _this.map.addChild(enemy);
                    }.bind(_this));
                    
                    
                    // 碰到敌人后删除子弹
                    bullet.parent.removeChild(bullet, true);
                    delete bulletMap[bulletKey];

                    // 碰到敌人后删除敌人
                    plane.parent.removeChild(plane, true);
                    delete planeMap[planeKey];
                    break;
                }
            }
        }
    },

    /**
     * 刷新敌人
     */
    refreshEnemy: function(dt){
         var _this = this;
        _this.refreshEnemyTime += dt;
        if(_this.refreshEnemyTime > _this.refreshTime){

        
         cc.loader.loadRes('persist/prefab/plane_enemy', function(err, prefab){
            var enemy = cc.instantiate(prefab);
            var randomPos = _this.upRandomPos();
            enemy.id        = _this.enemyValidId++;
            enemy.setPosition(randomPos);

            _this.map.addChild(enemy);
            _this.addEnemy(enemy);
            
        }.bind(_this)); // TODO：看看 bind 有什么用
        this.refreshEnemyTime = 0;
        }
        // this.refreshEnemyTime += dt;
        // if (this.refreshEnemyTime > this.gameStatus.refreshTime){
        //     game.dispatchEvent(game.GameEvent.ENEMY_ADD, {
        //         id: this.enemyValidId,
        //         x: Math.random() * this.map.size.x - this.map.size.x / 2,
        //         y: Math.random() * this.map.size.y - this.map.size.y / 2,
        //     });

        //     ++this.enemyValidId;
        //     this.refreshEnemyTime = 0;
        // }
    },
    upRandomPos: function(){
        var posX = Math.floor(Math.random() * 1500 - 750);
        var posY = Math.floor(Math.random() * 1000 - 500);
        
        var pos = cc.v2(posX,posY);
       
        return pos;
    },
});